<?php
namespace App\Wen\Utils;
use App\Lib\Uploads\UploadHandler;
use App\Models\WxAttachment;
use Illuminate\Support\Facades\Http;

class ApiUtils{

    public static function cos_review_query($cosClient, $Bucket, WxAttachment $attachment){
        $JobId = get_tmp_meta('attachment', $attachment->id, 'cos_review_video_job_id');
        try {
            $res = $cosClient->getDetectVideoResult(array(
                'Bucket' => $Bucket,
                'Key' => $JobId,
            ));
            $res = $res->toArray();
            $Response = _array_key($res, 'Response', []);
            if($Response){
                $JobsDetail = _array_key($Response, 'JobsDetail', []);
                $Result = _array_key($JobsDetail, 'Result', -1);
                $JobId = _array_key($JobsDetail, 'JobId', '');
                $ForbidState = _array_key($JobsDetail, 'ForbidState', -1);
                if($Result == 1){
                    // 判定为违规敏感文件
                    UploadHandler::del($attachment, true, 1);
                }else if($Result == 2){
                    if($ForbidState == 1 || $ForbidState == 2){
                        $attachment->state = $ForbidState == 1 ? 3 : 4;
                        $attachment->cos_review = 2;
                        $attachment->save();
                    }else{
                        UploadHandler::frozen($attachment);
                    }
                }else{
                    if($ForbidState == 1 || $ForbidState == 2){
                        $attachment->state = $ForbidState == 1 ? 3 : 4;
                        $attachment->cos_review = 2;
                        $attachment->save();
                    }else{
                        $attachment->cos_review = 0;
                        $attachment->save();
                    }
                }
            }
        } catch (\Exception $e) {
            _logger_(__file__, __line__, $e->getMessage());
        }

    }

    public static function cos_review_submit($cosClient, $Bucket, WxAttachment $attachment){
        try {
            //存储桶视频审核
            $result = $cosClient->detectVideo(array(
                'Bucket' => $Bucket,
                'Input' => array(
                    'Object' => $attachment->path,
                    'DataId' => $attachment->id,
//            'UserInfo' => array(
//                'TokenId' => '',
//                'Nickname' => '',
//                'DeviceId' => '',
//                'AppId' => '',
//                'Room' => '',
//                'IP' => '',
//                'Type' => '',
//                'ReceiveTokenId' => '',
//                'Gender' => '',
//                'Level' => '',
//                'Role' => '',
//            ),
//            'Encryption' => array(
//                'Algorithm' => '',
//                'Key' => '',
//                'IV' => '',
//                'KeyId' => '',
//                'KeyType' => 0,
//            ),
                ),
                'Conf' => array(
//            'BizType' => '', // 可选 定制化策略
                    'Callback' => env('APP_URL').'/api/v1/cos/review/callback', // 可选 回调URL
                    'DetectContent' => 1, // 可选 用于指定是否审核视频声音，当值为0时：表示只审核视频画面截图；值为1时：表示同时审核视频画面截图和视频声音。默认值为0。
//            'CallbackVersion' => 'Detail', // 可选 回调内容的结构，有效值：Simple（回调内容包含基本信息）、Detail（回调内容包含详细信息）。默认为 Simple。
                    'Snapshot' => array(
                        'Mode' => 'Average', // 可选 截帧模式，默认值为 Interval。Interval 表示间隔模式；Average 表示平均模式；Fps 表示固定帧率模式。
//                'TimeInterval' => 50, // 可选 视频截帧频率
                        'Count' => '4', // 视频截帧数量
                    ),
                'Freeze' => array(
                    'PornScore' => 80,
                    'AdsScore' => 80,
                    'PoliticsScore' => 80,
                    'TerrorismScore' => 80,
                ),
                ),
            ));
            $result = $result->toArray();
            $first_detail = $result['JobsDetail'];
            $attachment_id = _array_key($first_detail, 'DataId', 0);
            if($attachment->id != $attachment_id){
                _logger_(__file__, __line__, $result);
            }else{
                $State = _array_key($first_detail, 'State', '');
                if(!_empty_($State)){
                    if($State == 'Submitted'){
                        WxAttachment::where('id', $attachment->id)->update([
                            'cos_review' => 5
                        ]);
                        $JobId = _array_key($first_detail, 'JobId', '');
                        if(!_empty_($JobId) && is_string($JobId)){
                            update_tmp_meta('attachment', $attachment->id, 'cos_review_video_job_id', $JobId);
                        }
                    }else{
                        _logger_(__file__, __line__, $result);
                    }
                }else{
                    _logger_(__file__, __line__, $result);
                }
            }
        } catch (\Exception $e) {
            // 请求失败
            _logger_(__file__, __line__, $e->getMessage());
        }
    }

    public static function ali_request($appcode, $url, $data, $is_post = false, $as_form = false){
        if(_empty_($appcode)){
            return null;
        }
        if($is_post){
            if($as_form){
                $res = Http::withHeaders([
                    'Authorization' => 'APPCODE '.$appcode,
                ])->asForm()->post($url, $data);
            }else{
                $res = Http::withHeaders([
                    'Authorization' => 'APPCODE '.$appcode,
                ])->post($url, $data);
            }

        }else{
            if($as_form){
                $res = Http::withHeaders([
                    'Authorization' => 'APPCODE '.$appcode,
                ])->asForm()->get($url, $data);
            }else{
                $res = Http::withHeaders([
                    'Authorization' => 'APPCODE '.$appcode,
                ])->get($url, $data);
            }

        }
        if($res->successful()){
            return $res->json();
        }else{
            return null;
        }
    }



}
